package ru.yermak.bookkeeping.common;

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import ru.yermak.bookkeeping.model.User;
import ru.yermak.bookkeeping.model.Group;

import javax.swing.*;

/**
 * User: harrier
 * Date: Jan 10, 2009
 * Time: 8:26:05 PM
 */
@Component
public class BookkeepingLoginService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private BookkeeperState bookkeeperState;


    @Transactional(propagation = Propagation.REQUIRED)
    public boolean authenticate(String login, String password) {
        init();
        User user = userDao.getUserByLogin(login);
        if (user==null) return false;
        if (user.getPassword().equals(password)) {
            bookkeeperState.setUserId(user.getId());
            bookkeeperState.setGroupId(user.getGroup().getId());
            return true;
        }
        return false;
    }

    private void init() {
        User admin = userDao.getUserByLogin("admin");
        if (admin != null) {
            return;
        }
        Group group = new Group();
        group.setName("main");
        userDao.saveGroup(group);
        User user = new User();
        user.setLogin("admin");
        user.setPassword("admin");
        user.setGroup(group);
        userDao.saveUser(user);
    }

}
